package cc.mrbird.febs.accounting.service.impl;

import cc.mrbird.febs.accounting.entity.CompanyProject;
import cc.mrbird.febs.accounting.entity.Project;
import cc.mrbird.febs.common.entity.QueryRequest;
import cc.mrbird.febs.accounting.entity.Company;
import cc.mrbird.febs.accounting.mapper.CompanyMapper;
import cc.mrbird.febs.accounting.service.ICompanyService;
import cc.mrbird.febs.common.entity.Strings;
import cc.mrbird.febs.common.utils.FebsUtil;
import cc.mrbird.febs.system.entity.Role;
import cc.mrbird.febs.system.entity.User;
import cc.mrbird.febs.system.mapper.RoleMapper;
import cc.mrbird.febs.utils.CodeConstant;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.annotation.Propagation;
import lombok.RequiredArgsConstructor;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import javax.annotation.Resource;
import java.util.*;

/**
 *  Service实现
 *
 * @author baoyinlei
 * @date 2021-09-28 23:07:50
 */
@Service
@RequiredArgsConstructor
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
public class CompanyServiceImpl extends ServiceImpl<CompanyMapper, Company> implements ICompanyService {

    @Resource
    private RoleMapper roleMapper;
    @Resource
    private CompanyProjectServiceImpl companyProjectService;

    @Override
    public IPage<Company> findCompanys(QueryRequest request, Company company) {
        LambdaQueryWrapper<Company> queryWrapper = new LambdaQueryWrapper<>();
        if (Objects.nonNull(company) && StringUtils.isNotBlank(company.getCompanyName())) {
            queryWrapper.like(Company::getCompanyName, company.getCompanyName());
        }
        User id = FebsUtil.getCurrentUser();
        queryWrapper.eq(Company::getIsDeleted, 0);
        queryWrapper.orderByDesc(Company::getId);
        Page<Company> page = new Page<>(request.getPageNum(), request.getPageSize());
        return this.page(page, queryWrapper);
    }

    @Override
    public List<Company> findCompanys(Company company) {
	    LambdaQueryWrapper<Company> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Company::getIsDeleted, 0);
        queryWrapper.orderByDesc(Company::getId);
        boolean flag = FebsUtil.getCurrentUser().getUserId().equals(CodeConstant.specialUserId);
        // 需要根据权限查询公司
        if (!flag && company != null && company.getNeedPermission() != null && company.getNeedPermission()) {
            Role role = roleMapper.selectById(FebsUtil.getCurrentUser().getRoleId());
            List<String> perList = role.getCompanyPermission() == null ? Collections.singletonList("-1") : Arrays.asList(role.getCompanyPermission().split(","));
            queryWrapper.in(Company::getId, perList);
        }
		return this.baseMapper.selectList(queryWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean createCompany(Company company) {
        company.setCompanyCode(UUID.randomUUID().toString());
        company.setCreateBy(FebsUtil.getCurrentUser().getUsername());
//        company.setCreateBy(FebsUtil.getCurrentUser().getRoleId());
        LambdaQueryWrapper<Company> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Company::getIsDeleted, 0);
        List<Company> companies = this.getBaseMapper().selectList(queryWrapper);
        Set<String> companyNames = new HashSet<>();
        for (Company e : companies) {
            companyNames.add(e.getCompanyName().trim());
        }
        if (!companyNames.contains(company.getCompanyName().trim())) {
            this.save(company);
            return true;
        } else {
            return false;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateCompany(Company company) {
        LambdaQueryWrapper<Company> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Company::getIsDeleted, 0);
        List<Company> companies = this.getBaseMapper().selectList(queryWrapper);
        Set<String> companyNames = new HashSet<>();
        for (Company e : companies) {
            if (!e.getId().equals(company.getId())) {
                companyNames.add(e.getCompanyName().trim());
            }
        }
        if (!companyNames.contains(company.getCompanyName().trim())) {
            company.setModifyTime(new Date());
            company.setModifyBy(FebsUtil.getCurrentUser().getUsername());
            this.saveOrUpdate(company);
            return true;
        } else {
            return false;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteCompany(String companyIds) {
        List<String> list = Arrays.asList(companyIds.split(Strings.COMMA));
        list.forEach(e -> {
            Company company = new Company();
            company.setId(Long.parseLong(e));
            company.setIsDeleted(1);
            company.setModifyBy(FebsUtil.getCurrentUser().getUsername());
            company.setModifyTime(new Date());
            this.baseMapper.updateById(company);
        });

        LambdaQueryWrapper<CompanyProject> q = new LambdaQueryWrapper<>();
        q.in(CompanyProject::getCompanyId, list);
        companyProjectService.getBaseMapper().selectList(q);
	}
}
